/**
* Base Tree
* Date 2015年04月01日 12:00
* Creator TanShenghu
* Email tanshenghu@163.com
*/
define(function(require, exports, module){
    
    var $          = require( '$' ),
        Jstree     = require( '../lib/jstree/jstree' ),
        Common     = require( '../lib/common' );
    
    if( $('#checklablePage-style').length===0 ){
        $('head').append( '<link id="jstree-style" rel="stylesheet" href="/metaTree/js/lib/jstree/themes/default/style.min.css"><link id="checklablePage-style" rel="stylesheet" href="/metaTree/style/metaTree.css">' );
    }
    
    var HTMLSTRING = '<div id="Pop-container-wrap" class="marketListPage">\
        <div id="top-nav" class="top-nav"><label class="Ptitle">标签勾选</label></div>\
        <div class="stopBox"><label class="fieldName">标签搜索</label><div class="search-Box"><input type="text" name="keyword" placeholder="输入标签中英文名"><i title="搜索"></i></div></div>\
        <div class="Laside"></div>\
        <div id="Pop-content" class="Pop-content">\
            <div class="wz-box"><label class="custom_checkbox"><span class="checkboxbg-box"><i></i><input type="checkbox" class="checkAll"></span><span>全选当前标签</span></label><p class="treeWZ"></p></div><div class="list-Box"><ul class="clearfix"></ul><p class="errTip"><i class="errIco"></i><span class="conText"></span></p></div>\
            <div class="checkTagList"><div class="hideBox"><h3>已选标签</h3><ul class="clearfix"></ul><p class="errTip"><i class="errIco"></i><span class="conText"></span></p><p class="handle-Box"><a href="javascript:;" class="ui-btn1 J-submit">确定</a></p></div><p class="open-Bar side-out"></p></div>\
        </div>\
    </div>',
    PID = '', // pid 参数
    rootCatalogId = 0, // 根结点id
    curTreeId = 0; // 当前树栏目id
    
    var DataConfig = {},
        container  = $( HTMLSTRING ),
    
        pagefn = {
        cacheData: {
            leftNav: []
        },
        ele: {
            checkAll: {
                ele: container.find('.wz-box .custom_checkbox'),
                checked: function( bool ){
                    if( bool ){
                        this.ele.addClass('label-checked').find(':checkbox').prop('checked', true);
                    }else{
                        this.ele.removeClass('label-checked').find(':checkbox').prop('checked', false);
                    }
                    
                }
            },
            treebox: container.find('.Laside'),
            listBox: container.find('.list-Box'),
            checkTagList: container.find('.checkTagList')
        },
        /**
        *
        * 元素节点初始化
        *
        */
        eleinit: function(){
            
            var This = this;
            
            $.getJSON(DataConfig.treeData, {catalogId:57}, function( data ){
                // tree
                var treeData = data.tree.children;
                for(var i=0,l=treeData.length; i<l; i++){
                    delete( treeData[i].parent ); // 根目录，不需要parent，经测试id与parent不能同时并在于根结点
                }
                
                
                curTreeId = rootCatalogId = data.tree.children[0].id; // 默认取根结点id
                
                This.ele.treebox.jstree({
                    
                    'core': {
                        'data': treeData,
                        'check_callback' : true
                    },
                    'plugins' : ['wholerow']
                    
                }).bind('select_node.jstree', function(event, data) {              // click.jstree
                    //var eventNodeName = event.target.nodeName;               
                    var $this = $( event.target ), curDate = data.node, hasChild = curDate.children.length;
                        
                        curTreeId = curDate.id;
                        //if( hasChild==0 ){
                            This.LabelData( undefined, {catalogId: curDate.id} );
                        //}
                        
                        // 面包屑 结构
                        var _WZ = curDate.original.namePath[ curDate.id ];
                        _WZ[0]===PID && _WZ.shift(); // 删除第一项PID
                        
                        //parents ID前后互换
                        curDate.parents.unshift( curDate.parents.pop() );
                        
                        var arrlen = _WZ.length, HtmlStr = '';
                        for(var i=0; i<arrlen; i++){
                            
                            if( i===arrlen-1 ){
                                HtmlStr += '<span class="current" rel="'+curDate.parents[ i ]+'">'+_WZ[ i ]+'</span>';
                                continue;
                            }
                            HtmlStr += '<a href="javascript:;" rel="'+curDate.parents[ i ]+'">'+_WZ[ i ]+'</a> &gt; ';
                        }
                        container.find('.treeWZ').html( HtmlStr );
                });
                
            });
        },
        /**
        *
        * 请求标签数据
        *
        */
        LabelData: function( url, option, callback ){
            var This = this;
            option = $.extend( {pId: PID, level: '-1'}, option );
            
            url = url || DataConfig.getLabelUrl;
            
            This.ele.listBox.addClass('list-loading');
            
            $.getJSON(url, option, function( data ){
                var HtmlStr = '';
                This.action.showhasTip( This.ele.listBox.find('.errTip'), '0', '' ).hide();
                if( data.propertyList && data.propertyList.length ){
                    
                    $.each(data.propertyList, function(i, item){
                        var name    = item.chineseName || item.name,
                            findObj = This.ele.checkTagList.find('[data-id="'+item.id+'"]'),
                            len  = findObj.length && findObj.attr('data-catalogid') === item.catalogId;// 根据 标签id与catalogid验证两者都相同时归为同一标签
                        HtmlStr += (!len) ? '<li data-id="'+item.id+'" data-catalogid="'+item.catalogId+'"  title="'+name+'"><label class="custom_checkbox"><span class="checkboxbg-box"><i></i><input type="checkbox" autocomplete="off" value="'+item.id+'"></span><span class="txt">'+name+'</span></label><input type="hidden" class="J-cacheData" value=\''+JSON.stringify(item)+'\'></li>' : '<li data-id="'+item.id+'" data-catalogid="'+item.catalogId+'" class="label-checked"  title="'+name+'"><label class="custom_checkbox"><span class="checkboxbg-box"><i></i><input type="checkbox" checked="checked" autocomplete="off" value="'+item.id+'"></span><span class="txt">'+name+'</span></label><input type="hidden" class="J-cacheData" value=\''+JSON.stringify(item)+'\'></li>';
                        
                    });
                    
                }
                if( data.propertyList.length===0 ){

                    This.action.showhasTip( This.ele.listBox.find('.errTip'), '0', '当前结点下没有查到标签！' );

                }
                
                This.ele.listBox.find('ul').html( HtmlStr ).parent().removeClass('list-loading');
                
                // 是否全选
                var liLen = This.ele.listBox.find('ul li').length, checkedLen = This.ele.listBox.find('ul :checked').length;
                if( liLen>0 && liLen===checkedLen ){
                    This.ele.checkAll.checked( true );
                }else{
                    This.ele.checkAll.checked( false );
                }
                
                typeof callback === 'function' && callback.apply( data );
            });
        },
        /**
        *
        * 交互 动作 行为
        *
        */
        action: {
            
            /**
            *
            * 顶部 搜索
            *
            */
            search: function(){
                var This = this, _Fobj = This._Fobj;
                container.find('.search-Box i').on('click', function(){
                    var oinput = $(this).prevAll(':text'), kw = oinput.val().trim(), o = {};
                    o[ oinput.attr('name') ] = encodeURIComponent( kw );
                    o[ 'catalogId' ] = curTreeId;
                    if( kw ){
                        _Fobj.LabelData( DataConfig.searchPort, o );
                    }
                    
                }).prevAll(':text').on('keyup', function( ev ){
                    ev = ev || event;
                    if( ev.keyCode===13 || ev.which===13 || ev.charCode===13 ){
                        $(this).nextAll('i').trigger('click');
                    }
                });
            },
            /**
            *
            * 操作提示显示 
            *
            */
            showhasTip: function( errbox, type, txt ){
                errbox.show().attr( 'class', 'errTip Msg-'+(type||'0') ).find('.conText').text( (txt||'') );
                return errbox;
            },
            listCheckbox: function(){
                var This = this,
                _Fobj            = This._Fobj,
                checkTagList     = _Fobj.ele.checkTagList.find('ul'),
                listBox          = _Fobj.ele.listBox;
                
                /**
                *
                * 右侧展开与隐藏 
                *
                */
                _Fobj.ele.checkTagList.find('.open-Bar').on('click', function(){
                    var $this = $(this), w = parseInt( $this.parent().css('width') ) || 0;
                    var setW;
                    if( w===0 ){
                        setW = '240px';
                        $this.addClass('side-in').removeClass('side-out');
                    }else{
                        setW = '0';
                        $this.removeClass('side-in').addClass('side-out');
                    }
                    $this.prev('.hideBox').animate({width:setW}, 200);
                });
                
                /**
                *
                * 选择标签 
                *
                */
                listBox.on('change', 'li :checkbox', function(){
                    var $this = $(this), key = $this.val(), oli = $this.closest('li'), txt = oli.find('.txt').text(), labelDataStr = oli.find('.J-cacheData').val(), labelData= $.parseJSON( labelDataStr );
                    
                    if( $this.is(':checked') ){
                        
                        oli.addClass('label-checked');
                        var findObj = checkTagList.find('[data-id="'+key+'"]');
                        
                        if( findObj.length===0 || findObj.attr('data-catalogid')!==labelData.catalogId ){
                            checkTagList.append( '<li data-id="'+key+'" data-catalogid="'+labelData.catalogId+'" title="'+txt+'"><i title="删除" class="J-del"></i><span class="txt">'+txt+'</span><input type="checkbox" name="relationIds" class="undis" checked="checked" value="'+labelData.relationId+'"><input type="hidden" class="J-cacheData" value=\''+labelDataStr+'\'></li>' );
                        }
                        
                    }else{
                        oli.removeClass('label-checked');
                        var curObj = checkTagList.find('[data-id="'+key+'"]');
                        
                        curObj.each(function(i, ele){
                            var $this = $( this );
                            if( $this.attr('data-catalogid') === labelData.catalogId ){
                                $this.remove();
                            }
                        });
                        //checkTagList.find('[data-id="'+key+'"]').find('.J-del').click().trigger('click');
                    }
                    
                    // 全选对应的状态
                    if( listBox.find('li').length === listBox.find(':checked').length ){
                        _Fobj.ele.checkAll.checked( true );
                    }else{
                        _Fobj.ele.checkAll.checked( false );
                    }
                    
                });
                /**
                *
                * 删除标签 
                *
                */
                container.on('click', '.J-del', function(){
                    var $this = $(this), pobj = $this.parent(), key = pobj.attr('data-id');
                    pobj.remove();
                    listBox.find('[value="'+key+'"]').prop('checked', false).parent('label').removeClass('checked').parent('li').removeClass('label-checked');
                });
                
                /**
                *
                * 标签 全选 
                *
                */
                var fn_checkAll = function( bool ){
                    var list = listBox.find('ul li'), liStr = '';
                    list.each(function(i, ele){
                        var $this        = $( ele ), catalogid = $this.attr('data-catalogid'), id = $this.attr('data-id'),
                            txt          = $this.text(),
                            labelDataStr = $this.find('.J-cacheData').val(),
                            labelData    = $.parseJSON( labelDataStr ),
                            curObj       = checkTagList.find('[data-id="'+id+'"]'),
                            isexist      = curObj.length && curObj.attr('data-catalogid')===catalogid;
                            
                        if( bool ){
                            
                            if( !isexist ){
                                liStr += '<li data-id="'+id+'" data-catalogid="'+catalogid+'" title="'+txt+'"><i title="删除" class="J-del"></i><span class="txt">'+txt+'</span><input type="checkbox" name="relationIds" class="undis" checked="checked" value="'+labelData.relationId+'"><input type="hidden" class="J-cacheData" value=\''+labelDataStr+'\'></li>';
                            }
                            
                        }else{
                            
                            if( isexist ){
                                curObj.remove();
                            }
                            
                        }
                            
                    });
                    
                    bool && checkTagList.append( liStr );
                    
                    
                };
                container.find('.checkAll').on('click', function(){
                    var $this = $( this ), label = $this.closest('label');
                    if( $this.is(':checked') ){
                        label.addClass( 'label-checked' );
                        fn_checkAll( true );
                        listBox.find('li').addClass('label-checked').find(':checkbox').prop('checked', true);
                    }else{
                        label.removeClass( 'label-checked' );
                        fn_checkAll( false );
                        listBox.find('li').removeClass('label-checked').find(':checkbox').prop('checked', false);
                    }
                    
               
                });
                
                /**
                *
                * 面包屑 展开树型
                *
                */
                container.find('.wz-box .treeWZ').on('click', 'a', function(){

                    var id = $(this).attr('rel');
                    id!=='#' && _Fobj.ele.treebox.jstree( 'toggle_node', '#'+id );
                    
                });
                checkTagList.on('click', 'li .txt', function(){
                    
                    var id = $(this).attr('data-id');
                    _Fobj.ele.treebox.jstree( 'toggle_node', '#'+id );
                    
                });
                /**
                *
                * 提交所选标签 
                *
                */
                _Fobj.ele.checkTagList.find('.J-submit').on('click', function(){
                    var $this = $(this), hasLabel = checkTagList.find('li').length;
                    
                    // _bus树， 取groupId,catalogId
                    var getParam = function( oul ){
                        var result = [];
                        oul.find('li').each(function(i){
                            var $this = $( this ), cacheData = $.parseJSON( $this.find('.J-cacheData').val() );
                            
                            //result.push( JSON.stringify({"catalogId":cacheData.catalogId, "groupId":cacheData.groupId}) );
                            result.push( cacheData.relationId );
                            
                        });
                        return result.join(',');
                    }
                    if( $this.hasClass('disabled') ){return;}
                    $this.addClass( 'disabled' );
                    
                    //if( hasLabel>0 ){ // 没有选标签也能提交
                        
                        if( PID ){
                            var _O = {}, param = getParam( checkTagList );
                            _O[ 'pId' ] = PID;
                            _O[ 'rootCatalogId' ] = rootCatalogId;
                            _O[ 'relationIds' ] = param;
                            
                             _Fobj.ele.checkTagList.find('.errTip').attr('class', 'errTip').show().find('.conText').html( '<img src="/meta/style/images/pophandler_loading.gif"><span class="middle" style="color:red;padding-left:3px;">正在提交...</span>' );
                            
                            $.post(DataConfig.saveLabelPort, _O, function( data ){

                                This.showhasTip( _Fobj.ele.checkTagList.find('.errTip'), '1', '数据保存成功！' );
                                
                            }).error(function(){
                                This.showhasTip( _Fobj.ele.checkTagList.find('.errTip'), '0', '数据保存失败！' );
                            }).complete(function(){
                                $this.removeClass( 'disabled' );
                            });
                            
                        }else{

                            This.showhasTip( _Fobj.ele.checkTagList.find('.errTip'), '0', '机构信息缺失！' );

                        }
                        
                        
                    //}else{

                    //    This.showhasTip( container.find('.checkTagList .errTip'), '2', '请先选择标签之后再确定！' );

                    //}
                });
                
                
            },
            dragger: function(){
                
                var dragBar = container.find('.top-nav'), _O = {ON:false};
                
                $(document).on('mouseup', function(){
                    dragBar.css('cursor','default');
                    _O.ON = false;
                    
                }).on('mousemove', function( ev ){
                    ev = ev || event;
                    if( _O.ON ){
                        
                        var l = Math.min(ev.clientX - _O.L, _O.BW),
                            t = Math.min(ev.clientY - _O.T, _O.BH);
                            l = Math.max( l, 0 );
                            t = Math.max( t, 0 );
                        _O.dialog.css({left:l+'px', top:t+'px'});
                        
                    }
                    
                });
                dragBar.on('mousedown', function( ev ){
                    ev        = ev || event;
                    var $this = $( this );
                    $this.css('cursor','move');
                    
                    _O.L      = ev.clientX - $this.offset().left;
                    _O.T      = ev.clientY - $this.offset().top;
                    _O.dialog = dragBar.closest('.kuma-dialog');
                    _O.BW     = document.documentElement.clientWidth - _O.dialog.outerWidth( true );
                    _O.BH     = document.documentElement.clientHeight - _O.dialog.outerHeight( true );
                    _O.ON     = true;
                    
                    
                });
                
            },
            init: function(){
                
                // 搜索框
                this.search();
                
                // 列表选项 选择
                this.listCheckbox();
                
                this.dragger();

            }
        },
        /**
        *
        * 数据回显
        *
        */
        backRender: function( option ){
            var This = this;
            option = option || {pId: PID};
            $.getJSON(DataConfig.initShowLabel, option, function( data ){
                
                if( data.propertyList && data.propertyList.length ){
                    var htmlStr = '';
                    $.each(data.propertyList, function(i, item){
                        var name = item.chineseName || item.name, labelDataStr = JSON.stringify( item );
                        htmlStr += '<li data-id="'+item.id+'" data-catalogid="'+item.catalogId+'" title="'+name+'"><i title="删除" class="J-del"></i><span class="txt">'+name+'</span><input type="checkbox" name="relationIds" class="undis" checked="checked" value="'+item.relationId+'"><input type="hidden" class="J-cacheData" value=\''+labelDataStr+'\'></li>';
                    });
                    This.ele.checkTagList.find('ul').html( htmlStr );
                }
                
            });
        },
        init: function( paramPort ){
            
            // 传入接口参数
            DataConfig = paramPort || window.DataConfig;
            PID = DataConfig.PID// || window.DataConfig.PID;
            
            // 页面元素初始化
            this.eleinit();
            
            // 动作、行为
            this.action._Fobj = this;
            this.action.init();
            
            // 数据 回显
            this.backRender( );
            
        }
        
    };
    
    //pagefn.init( paramPort );
    
    /** 
    *  弹出层 
    */
    /*var popBox = new Dialog({
        trigger: '.showPop',
        content: container,
        width:900,
        height:500
    });*/
    
    return {
        content: container,
        init: pagefn
    };
    
    
});